/**
 * checkbox表单快速请求
 * checkbox
 */
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { Checkbox, Spin } from 'antd';
import { getEffectSource, everyRequire } from './utils';

const CheckboxForm = React.forwardRef(
    ({ onChange, value, getData, params, ...rest }, ref) => {
        const { checkboxProps, fieldsName, requireParam } = rest;
        const { checkboxValue, checkboxTitle } = fieldsName;
        const [checkboxList, setCheckboxList] = useState([]);
        const [loading, setLoading] = useState(false);
        const fetchList = async () => {
            if (!everyRequire(params, requireParam)) return;
            setLoading(true);
            const result = await getData(params);
            setLoading(false);
            setCheckboxList(result || []);
        };

        const handleChange = (e = '') => {
            onChange(e);
        };
        useEffect(() => {
            fetchList();
        }, getEffectSource(params));
        return (
            <Spin spinning={loading}>
                <Checkbox.Group
                    ref={ref}
                    // see: https://github.com/ant-design/ant-design/issues/6543
                    value={value}
                    onChange={handleChange}
                    {...checkboxProps}
                >
                    {/* <Row style={{ width: '100%' }}> */}
                    {checkboxList.map(item => (
                        // <Col span={6}>
                        <Checkbox value={item[checkboxValue]} key={item.id}>
                            {item[checkboxTitle]}
                        </Checkbox>
                        // </Col>
                    ))}
                    {/* </Row> */}
                </Checkbox.Group>
            </Spin>
        );
    }
);

CheckboxForm.propTypes = {
    onChange: PropTypes.func,
    /**
     * request 请求参数
     */
    params: PropTypes.object,
    /**
     * 获取数据
     */
    getData: PropTypes.func,
    /**
     * 自定义字段
     */
    fieldsName: PropTypes.object,
    // checkbox 属性
    checkboxProps: PropTypes.object
};

CheckboxForm.defaultProps = {
    onChange: () => {},
    checkboxProps: {},
    params: {},
    getData: () => {},
    fieldsName: {}
};

export default CheckboxForm;
